<template>
  <div
    style="
      width: 100%;
      height: 100%;
      background-color: #f0f2f5;
      padding: 20px 0 0;
    "
  >
    <!-- 开头 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card style="margin-bottom: 10px">
          {{ state.repoTitle }} 题库
          <el-button
            :loading="state.loading"
            style="float: right; margin-top: -10px"
            type="primary"
            size="large"
            @click="exitFun()"
          >
            退出重刷
          </el-button>
        </el-card>
      </el-col>

      <el-col :span="5" :xs="24" style="margin-bottom: 10px">
        <el-card class="content-h">
          <div class="btn_switch">
            <button
              class="btn_anniu"
              :class="{ newStyle: 0 === state.number }"
              @click="change(0)"
            >
              按顺序
            </button>
            <button
              class="btn_anniu"
              :class="{ newStyle: 1 === state.number }"
              @click="change(1)"
            >
              按题型
            </button>
            <div style="height: 20px" />
            <el-row :gutter="24" class="card-line" style="padding-left: 10px">
              <el-tag type="success">回答正确</el-tag>
              <el-tag type="danger">回答错误</el-tag>
              <el-tag type="info">未作答</el-tag>
              <el-tag type="warning">当前试题</el-tag>
              <div style="margin-bottom: 15px" />
            </el-row>
          </div>
          <!-- <div> -->
          <div v-if="0 === state.number">
            <!-- <p>我是题型</p> -->
            <p class="card-title">答题卡</p>
            <el-row :gutter="24" class="card-line" style="padding-left: 10px">
              <el-tag
                v-for="(item, index) in state.quList"
                :key="index"
                style="width: calc(100% / 8); text-align: center"
                :type="cardItemClass(item.exercised, item.quId, item.isRight)"
                @click="selectQuNum(item, index)"
                >{{ index + 1 }}</el-tag
              >
            </el-row>
          </div>

          <div v-if="1 === state.number">
            <div v-if="state.paperData.radioList.length > 0">
              <p class="card-title">单选题</p>
              <el-row :gutter="24" class="card-line">
                <el-tag
                  v-for="(item, index) in state.paperData.radioList"
                  :key="index"
                  :type="cardItemClass(item.exercised, item.quId, item.isRight)"
                  @click="selectQuId(item, index)"
                  >{{ index + 1 }}</el-tag
                >
              </el-row>
            </div>

            <div
              v-if="
                state.paperData.multiList !== undefined &&
                state.paperData.multiList.length > 0
              "
            >
              <p class="card-title">多选题</p>
              <el-row :gutter="24" class="card-line">
                <el-tag
                  v-for="(item, index) in state.paperData.multiList"
                  :key="index"
                  :type="cardItemClass(item.exercised, item.quId, item.isRight)"
                  @click="selectQuId(item, index)"
                  >{{ index + 1 }}</el-tag
                >
              </el-row>
            </div>

            <div
              v-if="
                state.paperData.judgeList !== undefined &&
                state.paperData.judgeList.length > 0
              "
            >
              <p class="card-title">判断题</p>
              <el-row :gutter="24" class="card-line">
                <el-tag
                  v-for="(item, index) in state.paperData.judgeList"
                  :key="index"
                  :type="cardItemClass(item.exercised, item.quId, item.isRight)"
                  @click="selectQuId(item, index)"
                  >{{ index + 1 }}</el-tag
                >
              </el-row>
            </div>
            <div
              v-if="
                state.paperData.saqList !== undefined &&
                state.paperData.saqList.length > 0
              "
            >
              <p class="card-title">简答题</p>
              <el-row :gutter="24" class="card-line">
                <el-tag
                  v-for="(item, index) in state.paperData.saqList"
                  :key="index"
                  :type="cardItemClass(item.exercised, item.quId, item.isRight)"
                  @click="selectQuId(item, index)"
                  >{{ index + 1 }}</el-tag
                >
              </el-row>
            </div>
          </div>

          <!-- </div> -->
        </el-card>
      </el-col>

      <el-col :span="19" :xs="24">
        <el-card class="qu-content content-h">
          <p v-if="state.quDetail.content">
            {{
              state.number == 1
                ? state.curTypeIndex + 1
                : state.currentQuIndex + 1
            }}.{{ state.quDetail.content }}
            {{ shouQuType(state.quDetail.quType) }}
          </p>
          <p v-if="state.quDetail.image != null && state.quDetail.image != ''">
            <el-image :src="state.quDetail.image" style="max-width: 100px" />
          </p>
          <div v-if="state.quDetail.quType == 1 || state.quDetail.quType == 3">
            <el-radio-group v-model="radioValue" class="full-width-group">
              <el-radio
                v-for="item in state.quDetail.options"
                :key="item.id"
                :value="item.id"
                :style="{
                  backgroundColor: radioValue === item.id ? '#ecf5ff' : '',
                  borderColor: radioValue === item.id ? '#409eff' : '#dcdfe6',
                  borderWidth: radioValue === item.id ? '2px' : '1px',
                }"
              >
                <span
                  :style="{
                    color: radioValue === item.id ? '#409eff' : '',
                    fontWeight: radioValue === item.id ? 'bold' : 'normal',
                  }"
              >{{ numberToLetter(item.sort + 1) }}.{{ item.content }}
                  <div
                    v-if="item.image != null && item.image != ''"
                    style="clear: both"
                  >
                  <el-image :src="item.image" style="max-width: 100px" />
                </div>
                </span>
              </el-radio>
            </el-radio-group>
          </div>

          <div v-if="state.quDetail.quType == 2">
            <el-checkbox-group v-model="multiValue" class="full-width-group">
              <el-checkbox
                v-for="item in state.quDetail.options"
                :key="item.id"
                :value="item.id"
                :style="{
                  backgroundColor: multiValue.includes(item.id)
                    ? '#ecf5ff'
                    : '',
                  borderColor: multiValue.includes(item.id)
                    ? '#409eff'
                    : '#dcdfe6',
                  borderWidth: multiValue.includes(item.id) ? '2px' : '1px',
                }"
              >
                <span
                  :style="{
                    color: multiValue.includes(item.id) ? '#409eff' : '',
                    fontWeight: multiValue.includes(item.id)
                      ? 'bold'
                      : 'normal',
                  }"
              >{{ numberToLetter(item.sort + 1) }}.{{ item.content }}
                  <div
                    v-if="item.image != null && item.image != ''"
                    style="clear: both"
                  >
                  <el-image :src="item.image" style="max-width: 100px" />
                </div>
                </span>
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="state.quDetail.quType === 4">
            <el-input
              v-model="radioValue"
              type="textarea"
              resize="none"
              :clearable="true"
              size="large"
              placeholder="请输入答案"
            />
          </div>

          <div v-if="state.rightQuAnswer.data != null">
            <p v-if="state.quDetail.quType != 4" style="margin: 10px 0">
              <el-tag
                size="large"
                :type="
                  state.rightQuAnswer.msg == '回答正确' ? 'success' : 'danger'
                "
                :class="{
                  'answer-tag': true,
                  'answer-correct': state.rightQuAnswer.msg == '回答正确',
                  'answer-wrong': state.rightQuAnswer.msg != '回答正确',
                }"
                >{{ state.rightQuAnswer.msg }}</el-tag
              >
            </p>

            <p v-if="state.rightQuAnswer.data">
              <span class="answer-label">正确答案：</span>
              <span class="correct-answer">{{ getRightAnswer() }}</span>
            </p>
            <p>
              <span class="answer-label">试题分析：</span>
              <span class="answer-analysis">{{
                state.rightQuAnswer.data.analysis
              }}</span>
            </p>
          </div>

          <div style="margin-top: 20px">
            <el-button
              v-if="state.showPrevious"
              type="primary"
              size="large"
              @click="handPrevious()"
            >
              <el-icon><ArrowLeft /></el-icon>
              上一题
            </el-button>

            <el-button
              v-if="state.showNext"
              type="warning"
              size="large"
              @click="handNext()"
            >
              下一题
              <el-icon><ArrowRight /></el-icon>
            </el-button>

            <el-button
              v-if="!state.showNext"
              type="success"
              size="large"
              @click="finishPractice()"
            >
              结束刷题
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getQuestion,
  getQuestionDetail,
  submitAnswer,
  getAnswerInfo,
} from '@/api/user/exampractice'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

const state = reactive({
      showAnalysis: 0,
  repoId: route.query.repoId,
  repoTitle: route.query.repoTitle,
      quId: '',
      curQuId: '',
      quList: [],
  quDetail: {
    content: '',
    quType: 0,
    image: '',
    options: [],
    repoId: '',
    id: '',
  },
      preText: '上一题',
  nextText: '下一题',
      rightQuAnswer: {},
      number: 0,
      receivedRow: null,
      curTypeIndex: 0,
      curListIndex: 1,
      isFullscreen: false,
      showPrevious: false,
      showNext: true,
      loading: false,
      handleText: '提交',
      pageLoading: false,
      currentQuIndex: 0,
      paperId: '',
      cardItem: {},
      allItem: [],
      quData: {
    answerList: [],
      },
      paperData: {
        radioList: [],
        multiList: [],
        judgeList: [],
    saqList: [],
  },
})

const radioValue = ref('')
const multiValue = ref([])
const answeredIds = ref([])

// 方法
const exitFun = async () => {
  try {
    await ElMessageBox.confirm('确定要退出刷题', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    state.handleText = '正在退出，请等待...'
    state.loading = true
    router.push({ path: '/student/practice' })
  } catch {
    ElMessage.info('退出已取消，您可以继续联系！')
  }
}

const test = async () => {
  const res = await getQuestion(null, state.repoId)
  state.quList = res.data

  state.paperData.radioList = []
  state.paperData.multiList = []
  state.paperData.judgeList = []
  state.paperData.saqList = []

  if (state.number == 1) {
    state.quList.forEach((item) => {
          if (item.quType == 1) {
        state.paperData.radioList.push(item)
          } else if (item.quType == 2) {
        state.paperData.multiList.push(item)
          } else if (item.quType == 3) {
        state.paperData.judgeList.push(item)
          } else if (item.quType == 4) {
        state.paperData.saqList.push(item)
      }
    })
    state.quList = []
    initQuId()
  }
  getCurrentQuDetial()
}

const numberToLetter = (sort) => {
  const letters = ['', 'A', 'B', 'C', 'D', 'E', 'F']
  return letters[sort] || ''
}

const change = (index) => {
  state.number = index
  state.preText = '上一题'
  state.nextText = '下一题'
  state.showAnalysis = 0
  getQuestionList()
  setTimeout(() => getCurrentQuDetial(), 200)
}

const getRightAnswer = () => {
  const arr = []
  if (state.rightQuAnswer.data) {
    state.rightQuAnswer.data.options.forEach((option) => {
      if (option.isRight) {
        arr.push(numberToLetter(option.sort + 1))
      }
    })
  }

  let res = arr.join(',')
  if (state.quDetail.quType == 4) {
    res = state.rightQuAnswer.data.options[0].content
  }
  return res
}

const getQuestionList = async () => {
  const res = await getQuestion(null, state.repoId)
  state.quList = res.data

  if (state.number == 1) {
    // 清空现有题目列表，避免重复添加
    state.paperData.radioList = []
    state.paperData.multiList = []
    state.paperData.judgeList = []
    state.paperData.saqList = []

    state.quList.forEach((item) => {
      if (item.quType == 1) {
        state.paperData.radioList.push(item)
      } else if (item.quType == 2) {
        state.paperData.multiList.push(item)
      } else if (item.quType == 3) {
        state.paperData.judgeList.push(item)
      } else if (item.quType == 4) {
        state.paperData.saqList.push(item)
      }
    })
    state.quList = []
    initQuId()
  }
}

const selectQuId = (item, index) => {
  state.curTypeIndex = index
  state.curQuId = item.quId
      if (item.quType == 1) {
    state.curListIndex = 1
      } else if (item.quType == 2) {
    state.curListIndex = 2
      } else if (item.quType == 3) {
    state.curListIndex = 3
      } else if (item.quType == 4) {
    state.curListIndex = 4
  }

  // 清空之前的答案和答案反馈
  radioValue.value = ''
  multiValue.value = []
  state.rightQuAnswer = {}

  // 获取题目详情
  getCurrentQuDetial().then(() => {
    // 如果题目已作答，获取答案信息
    if (item.exercised) {
      getAnswerInfo(item.repoId, item.quId)
        .then((res) => {
          if (res && res.data) {
            state.rightQuAnswer = res

            // 根据题型设置选中值
            if (res.data.quType == 1 || res.data.quType == 3) {
              radioValue.value = parseInt(res.data.answerContent)
            } else if (res.data.quType == 4) {
              radioValue.value = res.data.answerContent
            } else if (res.data.quType == 2 && res.data.answerContent) {
              setMultiValues(res)
            }
          }
        })
        .catch((error) => {
          console.error('获取答案信息失败:', error)
        })
    }
  })
}

const getCurrentQuDetial = async () => {
  const loading = ElLoading.service({
    text: '拼命加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    if (state.number == 0 && state.quList.length > 0) {
      const res = await getQuestionDetail(
        state.quList[state.currentQuIndex].quId
      )
      state.quDetail = res.data || state.quDetail
    } else if (state.number == 1 && state.curQuId) {
      const res = await getQuestionDetail(state.curQuId)
      state.quDetail = res.data || state.quDetail
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
  } finally {
      loading.close()
  }
}

const cardItemClass = (answered, id, isright) => {
  // 判断是否为当前题目
  const isCurrentQuestion = id === state.quDetail.id

  if (isCurrentQuestion) {
        return 'warning'
      } else if (isright) {
        return 'success'
      } else if (answered) {
        return 'danger'
      } else {
        return 'info'
      }
}

const initQuId = () => {
  state.curQuId = state.paperData.radioList[0].quId
}

const initCurrentIndex = () => {
      var exercisedCount = 0

      setTimeout(() => {
    state.quList.forEach((element) => {
          if (element.exercised) {
        state.currentQuIndex++
            exercisedCount++
          }
      if (exercisedCount == state.quList.length) {
        state.currentQuIndex = 0
          }
        })
    showButton()
      }, 100)
}

const selectQuNum = (item, index) => {
  const loading = ElLoading.service({
        text: '拼命加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  state.preText = '上一题'
  state.nextText = '下一题'
  state.showAnalysis = 0
  radioValue.value = ''
  multiValue.value = []
  state.rightQuAnswer = {} // 清空上一题的答案信息
  state.currentQuIndex = index
  showButton()

  // 先获取题目详情
  getCurrentQuDetial().then(() => {
    // 只有对已作答的题目，才获取答案信息和显示解析
    if (item.exercised) {
      getAnswerInfo(
        state.quList[state.currentQuIndex].repoId,
        state.quList[state.currentQuIndex].quId
      )
        .then((res) => {
          if (res && res.data) {
            state.rightQuAnswer = res

            // 根据题型设置选中值
            if (res.data.quType == 1 || res.data.quType == 3) {
              radioValue.value = parseInt(res.data.answerContent)
            } else if (res.data.quType == 4) {
              radioValue.value = res.data.answerContent
            } else if (res.data.quType == 2 && res.data.answerContent) {
              setMultiValues(res)
            }
          }
        })
        .catch((error) => {
          console.error('获取答案信息失败:', error)
        })
    }
  })

      loading.close()
}

// 辅助函数：设置多选值
const setMultiValues = (res) => {
  if (res.data.answerContent && res.data.options) {
    const arr = res.data.answerContent.split(',')
    multiValue.value = []
    arr.forEach((element) => {
      for (let index = 0; index < res.data.options.length; index++) {
        const option = res.data.options[index]
        if (parseInt(element) == option.id) {
          multiValue.value.push(option.id)
        }
      }
    })
  }
}

const shouQuType = (type) => {
      if (type == 1) {
        return '(单选题)'
      } else if (type == 2) {
        return '(多选题)'
      } else if (type == 3) {
        return '(判断题)'
      } else if (type == 4) {
        return '(简答题)'
      }
}

const fillAnswer = async () => {
  // 检查题目详情是否存在
  if (!state.quDetail || !state.quDetail.id) {
    console.error('题目信息不完整，无法提交答案')
    return null
  }

  let params = {
    repoId: state.quDetail.repoId,
    quId: state.quDetail.id,
    quType: parseInt(state.quDetail.quType),
  }

  // 根据题型设置答案 - 确保使用 .value 获取 ref 的值
  if (
    state.quDetail.quType == 1 ||
    state.quDetail.quType == 3 ||
    state.quDetail.quType == 4
  ) {
    params.answer = radioValue.value
  } else if (state.quDetail.quType == 2 && Array.isArray(multiValue.value)) {
    params.answer = multiValue.value.join(',')
  }

  console.log('提交的答案参数:', params)

  try {
    const res = await submitAnswer(params)
    state.rightQuAnswer = res

    // 更新当前题目的做题状态
    if (state.number == 0) {
      // 按顺序模式：更新quList中的状态
      if (state.quList && state.quList[state.currentQuIndex]) {
        state.quList[state.currentQuIndex].exercised = true
        state.quList[state.currentQuIndex].isRight = res.msg === '回答正确'
      }
    } else if (state.number == 1) {
      // 按题型模式：更新对应题型列表中的状态
      updateQuestionStatusByType(state.quDetail.id, res.msg === '回答正确')
    }

    return res
  } catch (error) {
    console.error('提交答案失败:', error)
    ElMessage.error('答案提交失败，请重试')
    throw error // 出错时中断流程
  }
}

// 按题型模式下更新题目状态的辅助函数
const updateQuestionStatusByType = (quId, isRight) => {
  // 遍历所有题型列表，查找并更新对应题目的状态
  const updateInList = (list) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].quId === quId) {
        list[i].exercised = true
        list[i].isRight = isRight
        return true
      }
    }
    return false
  }

  // 尝试在各题型列表中查找并更新
  if (updateInList(state.paperData.radioList)) return
  if (updateInList(state.paperData.multiList)) return
  if (updateInList(state.paperData.judgeList)) return
  if (updateInList(state.paperData.saqList)) return
}

const handNext = async () => {
  // 移除必须选择答案的检查
  const loading = ElLoading.service({
        text: '拼命加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    // 如果用户选择了答案，则提交
    let hasAnswer = false
    if (state.quDetail.quType == 1 || state.quDetail.quType == 3) {
      hasAnswer =
        radioValue.value !== '' &&
        radioValue.value !== null &&
        radioValue.value !== undefined
    } else if (state.quDetail.quType == 2) {
      hasAnswer = Array.isArray(multiValue.value) && multiValue.value.length > 0
    } else if (state.quDetail.quType == 4) {
      hasAnswer =
        radioValue.value !== '' &&
        radioValue.value !== null &&
        radioValue.value !== undefined
    }

    // 只有在用户选择了答案时才提交
    if (hasAnswer) {
      await fillAnswer()
    }

    // 切换到下一题
    radioValue.value = ''
    multiValue.value = []
    state.showAnalysis = 0
    state.rightQuAnswer = {} // 清空上一题的答案信息

    if (state.number == 0) {
      if (
        state.quList &&
        Array.isArray(state.quList) &&
        state.currentQuIndex < state.quList.length - 1
      ) {
        state.currentQuIndex++
      }
    } else if (state.number == 1) {
      // 原有的按题型切换逻辑保持不变
      if (state.curListIndex == 1 && state.paperData.radioList) {
        state.curTypeIndex++
        if (state.curTypeIndex >= state.paperData.radioList.length) {
          state.curListIndex = 2
          state.curTypeIndex = 0
          state.curQuId =
            state.paperData.multiList && state.paperData.multiList.length > 0
              ? state.paperData.multiList[0].quId
              : ''
            } else {
          state.curQuId = state.paperData.radioList[state.curTypeIndex].quId
        }
      } else if (state.curListIndex == 2 && state.paperData.multiList) {
        state.curTypeIndex++
        if (state.curTypeIndex >= state.paperData.multiList.length) {
          state.curListIndex = 3
          state.curTypeIndex = 0
          state.curQuId =
            state.paperData.judgeList && state.paperData.judgeList.length > 0
              ? state.paperData.judgeList[0].quId
              : ''
            } else {
          state.curQuId = state.paperData.multiList[state.curTypeIndex].quId
        }
      } else if (state.curListIndex == 3 && state.paperData.judgeList) {
        state.curTypeIndex++
        if (state.curTypeIndex >= state.paperData.judgeList.length) {
          state.curListIndex = 4
          state.curTypeIndex = 0
          state.curQuId =
            state.paperData.saqList && state.paperData.saqList.length > 0
              ? state.paperData.saqList[0].quId
              : ''
            } else {
          state.curQuId = state.paperData.judgeList[state.curTypeIndex].quId
        }
      } else if (state.curListIndex == 4 && state.paperData.saqList) {
        state.curTypeIndex++
        if (state.curTypeIndex >= state.paperData.saqList.length) {
          state.curListIndex = 1
          state.curTypeIndex = 0
          state.curQuId =
            state.paperData.radioList && state.paperData.radioList.length > 0
              ? state.paperData.radioList[0].quId
              : ''
            } else {
          state.curQuId = state.paperData.saqList[state.curTypeIndex].quId
        }
      }
    }

    // 获取新题目并更新UI
    await getCurrentQuDetial()

    // 只有当新题目已经做过时，才获取答案信息
    if (
      (state.number == 0 &&
        state.quList &&
        state.quList[state.currentQuIndex] &&
        state.quList[state.currentQuIndex].exercised) ||
      (state.number == 1 && state.curQuId && isQuestionAnswered(state.curQuId))
    ) {
      try {
        const repoId =
          state.number == 0
            ? state.quList[state.currentQuIndex].repoId
            : state.quDetail.repoId

        const quId =
          state.number == 0
            ? state.quList[state.currentQuIndex].quId
            : state.curQuId

        const res = await getAnswerInfo(repoId, quId)

        if (res && res.data) {
          state.rightQuAnswer = res

          // 设置选中值
          if (res.data.quType == 1 || res.data.quType == 3) {
            radioValue.value = parseInt(res.data.answerContent)
          } else if (res.data.quType == 4) {
            radioValue.value = res.data.answerContent
          } else if (res.data.quType == 2 && res.data.answerContent) {
            setMultiValues(res)
          }
        }
      } catch (error) {
        console.error('获取答案信息失败:', error)
      }
    }

    // 移除对getQuestionList的调用，避免重复获取题目导致数量增加
    // await getQuestionList()
    showButton()
  } catch (error) {
    console.error('处理下一题时出错:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
      loading.close()
  }
}

// 判断题目是否已作答的辅助函数
const isQuestionAnswered = (quId) => {
  // 在各题型列表中查找题目
  const findInList = (list) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].quId === quId) {
        return list[i].exercised
      }
    }
    return false
  }

  // 依次在各题型列表中查找
  return (
    findInList(state.paperData.radioList) ||
    findInList(state.paperData.multiList) ||
    findInList(state.paperData.judgeList) ||
    findInList(state.paperData.saqList)
  )
}

const showButton = () => {
  if (state.currentQuIndex === 0) {
    state.showPrevious = false
      } else {
    state.showPrevious = true
  }

  if (
    state.currentQuIndex === state.quList.length - 1 &&
    state.nextText === '下一题'
  ) {
    state.showNext = false
      } else {
    state.showNext = true
  }
}

const handPrevious = async () => {
  const loading = ElLoading.service({
        text: '拼命加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    radioValue.value = ''
    multiValue.value = []
    state.rightQuAnswer = {}

    if (state.currentQuIndex > 0) {
      state.currentQuIndex--
      showButton()

      // 先获取题目详情
      await getCurrentQuDetial()

      // 然后再获取答案信息
      if (state.quList[state.currentQuIndex].exercised) {
        const res = await getAnswerInfo(
          state.quList[state.currentQuIndex].repoId,
          state.quList[state.currentQuIndex].quId
        )

        if (res && res.data) {
          state.rightQuAnswer = res

          // 根据题型设置选中值
          if (res.data.quType == 1 || res.data.quType == 3) {
            radioValue.value = parseInt(res.data.answerContent)
          } else if (res.data.quType == 4) {
            radioValue.value = res.data.answerContent
          } else if (res.data.quType == 2 && res.data.answerContent) {
            const arr = res.data.answerContent.split(',')
            multiValue.value = []
            arr.forEach((element) => {
                for (let index = 0; index < res.data.options.length; index++) {
                const option = res.data.options[index]
                if (parseInt(element) == option.id) {
                  multiValue.value.push(option.id)
                }
              }
            })
          }
        }
      }
    }
  } catch (error) {
    console.error('处理上一题出错:', error)
    ElMessage.error('获取上一题失败，请重试')
  } finally {
    loading.close()
  }
}

const finishPractice = async () => {
  try {
    await ElMessageBox.confirm('确定要结束刷题吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 检查是否有答案需要提交
    let hasAnswer = false
    if (state.quDetail.quType == 1 || state.quDetail.quType == 3) {
      hasAnswer =
        radioValue.value !== '' &&
        radioValue.value !== null &&
        radioValue.value !== undefined
    } else if (state.quDetail.quType == 2) {
      hasAnswer = Array.isArray(multiValue.value) && multiValue.value.length > 0
    } else if (state.quDetail.quType == 4) {
      hasAnswer =
        radioValue.value !== '' &&
        radioValue.value !== null &&
        radioValue.value !== undefined
    }

    // 如果有答案，先提交当前题目
    if (hasAnswer) {
      const loading = ElLoading.service({
        text: '正在提交答案...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      try {
        await fillAnswer()
      loading.close()
      } catch (error) {
        loading.close()
        ElMessage.error('答案提交失败，请重试')
        return
      }
    }

    // 提交成功后退出
    state.loading = true
    router.push({ path: '/student/practice' })
  } catch {
    ElMessage.info('已取消结束刷题')
  }
}

// 初始化
onMounted(() => {
  test()
})

// 导出需要在模板中使用的变量和方法
defineExpose({
  state,
  radioValue,
  multiValue,
  exitFun,
  numberToLetter,
  change,
  getRightAnswer,
  getQuestionList,
  selectQuId,
  getCurrentQuDetial,
  cardItemClass,
  initQuId,
  initCurrentIndex,
  selectQuNum,
  shouQuType,
  handNext,
  fillAnswer,
  showButton,
  handPrevious,
  finishPractice,
})
</script>

<style scoped>
page {
  background: #ebecee;
}

.btn_anniu {
  width: 50%;
  padding: 10px 0;
  font-size: 19px;
  font-weight: bold;
  border: 0 solid #fff;
  color: #000;
  outline: none;
  background: #fff;
}

.newStyle {
  border-bottom: 2px solid #f0892e;
  color: #f0892e;
  font-size: 21px;
  font-weight: bold;
}

.qu-content div {
  line-height: 30px;
  width: 100%;
}

.el-checkbox-group label,
.el-radio-group label {
  width: 100%;
}

.content-h {
  height: calc(100vh - 110px);
  overflow-y: auto;
  width: 100%;
}

.qu-content {
  width: 100%;
}

.el-radio-group,
.el-checkbox-group {
  width: 100%;
  display: block;
}

::v-deep .el-radio,
::v-deep .el-checkbox {
  padding: 12px 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
  width: 100%;
  display: block;
  box-sizing: border-box;
}

.is-checked {
  border: #409eff 2px solid !important;
  background-color: #ecf5ff !important;
}

.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}

.card-line {
  padding-left: 10px;
}

.card-line span {
  cursor: pointer;
  margin: 2px;
}

.answer-label {
  font-weight: bold;
  color: #333;
  margin-right: 5px;
}

.correct-answer {
  display: inline-block;
  background-color: #f0f9eb;
  color: #67c23a;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #c2e7b0;
  font-size: 16px;
}

.answer-tag {
  font-weight: bold !important;
  font-size: 16px !important;
  padding: 6px 12px !important;
  letter-spacing: 1px !important;
}

.answer-correct {
  background-color: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}

.answer-wrong {
  background-color: #fef0f0 !important;
  border-color: #fbc4c4 !important;
}

.answer-analysis {
  display: inline-block;
  background-color: #f4f4f5;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #e9e9eb;
  line-height: 1.5;
  width: 100%;
  margin-top: 4px;
}

.el-radio img,
.el-checkbox img {
  max-width: 200px;
  max-height: 200px;
  border: #dcdfe6 1px dotted;
}

:deep(.el-checkbox__inner),
:deep(.el-radio__inner) {
  display: none;
}

:deep(.el-checkbox__label),
:deep(.el-radio__label) {
  line-height: 30px;
}

/* 为选项添加背景色 - 修复选择器优先级问题 */
:deep(.el-radio.answered-right),
:deep(.el-checkbox.answered-right) {
  background-color: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}

:deep(.el-radio.answered-right .el-radio__label),
:deep(.el-checkbox.answered-right .el-checkbox__label) {
  color: #67c23a !important;
  font-weight: bold !important;
}

:deep(.el-radio.answered-wrong),
:deep(.el-checkbox.answered-wrong) {
  background-color: #fef0f0 !important;
  border-color: #fbc4c4 !important;
}

:deep(.el-radio.answered-wrong .el-radio__label),
:deep(.el-checkbox.answered-wrong .el-checkbox__label) {
  color: #f56c6c !important;
  font-weight: bold !important;
}

:deep(.el-radio.right-option),
:deep(.el-checkbox.right-option) {
  background-color: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}

:deep(.el-radio.right-option .el-radio__label),
:deep(.el-checkbox.right-option .el-checkbox__label) {
  color: #67c23a !important;
  font-weight: bold !important;
}

:deep(.el-radio.is-checked),
:deep(.el-checkbox.is-checked) {
  border: #409eff 2px solid !important;
  background-color: #ecf5ff !important;
}

:deep(.el-radio.is-checked .el-radio__label),
:deep(.el-checkbox.is-checked .el-checkbox__label) {
  color: #409eff !important;
  font-weight: bold !important;
}

.wrong-answer-button {
  font-weight: bold;
  font-size: 16px;
  padding: 8px 15px;
  margin: 5px 0 10px 0;
}

.answer-buttons {
  margin: 15px 0;
}

.full-width-group {
  width: 100%;
  display: block;
}

:deep(.el-radio) {
  height: auto;
  margin: 10px 0;
  width: 100%;
  display: block;
  padding: 12px 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
}

:deep(.el-checkbox) {
  height: auto;
  margin: 10px 0;
  width: 100%;
  display: block;
  padding: 12px 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
}

:deep(.el-radio__label),
:deep(.el-checkbox__label) {
  white-space: normal;
  word-break: break-word;
  color: inherit;
}

/* 选中状态的文字颜色 */
:deep(.el-radio.is-checked),
:deep(.el-checkbox.is-checked) {
  border: #409eff 2px solid !important;
  background-color: #ecf5ff !important;
}

:deep(.el-radio.is-checked .el-radio__label span),
:deep(.el-checkbox.is-checked .el-checkbox__label span) {
  color: #409eff !important;
  font-weight: bold !important;
}
</style>
